package emp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jfinal.aop.Duang;
import com.jfinal.kit.Ret;
import common.model.*;
import layuiTable.*;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

public class EmpService {

    public static final EmpService me = Duang.duang(EmpService.class);
    private static final User userDao = new User().dao();
    private static final Department departmentDao = new Department().dao();
    private static final Entry entryDao = new Entry().dao();
    private static final Dimission dimissionDao = new Dimission().dao();
    private static final Tranfer transferDao = new Tranfer().dao();

    public List<Department> getDepartmentByUser(User user) {
        if (user.getAdmin()) {
            return departmentDao.find(departmentDao.getSql("department.findAll"));
        }

        int department = user.getDepartment();
        return departmentDao.find(departmentDao.getSqlPara("department.findByUser", department));
    }

    public List<User> getUserByUser(User user) {
        if (user.getAdmin()) {
            return userDao.find(userDao.getSql("user.findAll"));
        }
        if (user.getLevel().equals("部门经理")) {
            return userDao.find(userDao.getSqlPara("user.findByDepartment", user.getDepartment()));
        }
        List<User> ret = new LinkedList<User>();
        ret.add(user);
        return ret;
    }

    public List<User> getWorkUserByUser(User user) {
        if (user.getAdmin()) {
            return userDao.find(userDao.getSql("user.findAllWork"));
        }
        if (user.getLevel().equals("部门经理")) {
            return userDao.find(userDao.getSqlPara("user.findWorkByDepartment", user.getDepartment()));
        }
        List<User> ret = new LinkedList<User>();
        if (!user.getState().equals("离职")) {
            ret.add(user);
        }
        return ret;
    }

    public String getUserStringByUserAndDepartment(User user, int department) {
        List<User> users = getUserByUser(user);
        if (department != 0) {

            List<User> ret = new LinkedList<User>();
            for (User user1 : users) {
                if (user1.getDepartment() == department) {
                    ret.add(user1);
                }
            }

            return JSON.toJSONString(new layuiTableData(0, "", ret.size(), ret), SerializerFeature.WriteDateUseDateFormat);
        }

        return JSON.toJSONString(new layuiTableData(0, "", users.size(), users), SerializerFeature.WriteDateUseDateFormat);
    }

    public String getSearchUserStringByUserAndDepartment(User user, int department, int search) {
        List<User> users = getUserByUser(user);
        List<User> ret = new LinkedList<User>();
        if (department != 0) {
            for (User user1 : users) {
                if (user1.getDepartment() == department && user1.getId() == search) {
                    ret.add(user1);
                }
            }
        } else {

            for (User user1 : users) {
                if (user1.getId() == search) {
                    ret.add(user1);
                }
            }
        }

        return JSON.toJSONString(new layuiTableData(0, "", ret.size(), ret), SerializerFeature.WriteDateUseDateFormat);
    }

    public String getWorkUserStringByUserAndDepartment(User user, int department) {
        List<User> users = getWorkUserByUser(user);
        if (department != 0) {
            List<User> ret = new LinkedList<User>();
            for (User user1 : users) {
                if (user1.getDepartment() == department) {
                    ret.add(user1);
                }
            }

            return JSON.toJSONString(new layuiTableData(0, "", ret.size(), ret), SerializerFeature.WriteDateUseDateFormat);
        }

        return JSON.toJSONString(new layuiTableData(0, "", users.size(), users), SerializerFeature.WriteDateUseDateFormat);
    }

    public String getSearchWorkUserStringByUserAndDepartment(User user, int department, int search) {

        List<User> users = getWorkUserByUser(user);
        List<User> ret = new LinkedList<User>();
        if (department != 0) {
            for (User user1 : users) {
                if (user1.getDepartment() == department && user1.getId() == search) {
                    ret.add(user1);
                }
            }
        } else {

            for (User user1 : users) {
                if (user1.getId() == search) {
                    ret.add(user1);
                }
            }
        }

        return JSON.toJSONString(new layuiTableData(0, "", ret.size(), ret), SerializerFeature.WriteDateUseDateFormat);
    }

    public String getDepartmentStringByUser(User user) {
        List<Department> departments = getDepartmentByUser(user);
        return JSON.toJSONString(new layuiTableDepartment(0, "", departments.size(), departments), SerializerFeature.WriteDateUseDateFormat);
    }

    public String getStringDepartmentStringByUser(User user, int search) {
        List<Department> departments = getDepartmentByUser(user);
        List<Department> ret = new LinkedList<Department>();
        for (Department department : departments) {
            if (department.getId() == search) {
                ret.add(department);
            }
        }

        return JSON.toJSONString(new layuiTableDepartment(0, "", ret.size(), ret), SerializerFeature.WriteDateUseDateFormat);
    }

    public List<Entry> getEntryByUser(User user) {
        if (user.getAdmin()) {
            return entryDao.find(entryDao.getSql("entry.findAll"));
        }
        if (user.getLevel().equals("部门经理")) {
            return entryDao.find(entryDao.getSqlPara("entry.findByDepartment", user.getDepartment()));
        }
        return entryDao.find(entryDao.getSqlPara("entry.findByUser", user.getId()));
    }

    public String getEntryStringByUser(User user) {
        List<Entry> entries = getEntryByUser(user);
        return JSON.toJSONString(new layuiTableEntry(0, "", entries.size(), entries), SerializerFeature.WriteDateUseDateFormat);
    }

    public String getSearchEntryStringByUser(User user, int search) {
        List<Entry> entries = getEntryByUser(user);
        List<Entry> ret = new LinkedList<Entry>();
        for (Entry entry : entries) {
            if (entry.getEmp() == search) {
                ret.add(entry);
            }
        }

        return JSON.toJSONString(new layuiTableEntry(0, "", ret.size(), ret), SerializerFeature.WriteDateUseDateFormat);
    }

    public List<Tranfer> getTransferByUser(User user) {
        if (user.getAdmin()) {
            return transferDao.find(transferDao.getSql("transfer.findAll"));
        }
        if (user.getLevel().equals("部门经理")) {
            List<Tranfer> tranfers = transferDao.find(transferDao.getSql("transfer.findAll"));
            List<Tranfer> ret = new LinkedList<Tranfer>();
            for (Tranfer one : tranfers) {
                User emp = userDao.findById(one.getEmp());
                if (emp.getDepartment() == user.getDepartment()) {
                    ret.add(one);
                }
            }
            return ret;
        }
        return transferDao.find(transferDao.getSqlPara("transfer.findByUser", user.getId()));
    }

    public String getTransferStringByUser(User user) {
        List<Tranfer> tranfers = getTransferByUser(user);
        return JSON.toJSONString(new layuiTableTransfer(0, "", tranfers.size(), tranfers), SerializerFeature.WriteDateUseDateFormat);
    }

    public String getSearchTranserStringByUser(User user, int search) {
        List<Tranfer> tranfers = getTransferByUser(user);
        List<Tranfer> ret = new LinkedList<Tranfer>();
        for (Tranfer tranfer : tranfers) {
            if (tranfer.getEmp() == search) {
                ret.add(tranfer);
            }
        }
        return JSON.toJSONString(new layuiTableTransfer(0, "", ret.size(), ret), SerializerFeature.WriteDateUseDateFormat);

    }

    public List<Dimission> getDimissionByUserAndStatus(User user, String status) {
        List<Dimission> dimissions;
        if (status.equals("全部")) {
            dimissions = dimissionDao.find(dimissionDao.getSqlPara("dimission.findAllByUser", user.getId()));
        } else {
            if (user.getAdmin()) {
                dimissions = dimissionDao.find(dimissionDao.getSqlPara("dimission.findAllByStatus", status));
            } else if (user.getLevel().equals("部门经理")) {
                dimissions = dimissionDao.find(dimissionDao.getSqlPara("dimission.findAllByDepartmentAndStatus", user.getDepartment(), status));
            } else {
                dimissions = dimissionDao.find(dimissionDao.getSqlPara("dimission.findAllByUserAndStatus", user.getId(), status));
            }
        }
        return dimissions;
    }

    public List<Dimission> getCheckedDimissionByUser(User user) {
        List<Dimission> dimissions;
        if (user.getAdmin()) {
            dimissions = dimissionDao.find(dimissionDao.getSqlPara("dimission.findChecked"));
        } else if (user.getLevel().equals("部门经理")) {
            dimissions = dimissionDao.find(dimissionDao.getSqlPara("dimission.findCheckedByDepartment", user.getDepartment()));
        } else {
            dimissions = dimissionDao.find(dimissionDao.getSqlPara("dimission.findCheckedByUser", user.getId()));
        }

        return dimissions;
    }

    public String getDimissionStringByUserAndStatus(User user, String status) {

        List<Dimission> dimissions;
        if (status.equals("已处理")) {
            dimissions = getCheckedDimissionByUser(user);
        } else {

            dimissions = getDimissionByUserAndStatus(user, status);
        }
        return JSON.toJSONString(new layuiTableDimission(0, "", dimissions.size(), dimissions), SerializerFeature.WriteDateUseDateFormat);
    }

    public Ret newEmp(String username, String pwd, String gender, Date birthday, Date recordTime, String idCard, String area, String nativePlace, String state, int department, String leve, boolean admin) {
        User user = new User();
        if (!userDao.find(userDao.getSqlPara("user.findByUsername", username)).isEmpty()) {
            return Ret.by("status", false).set("msg", "用户名已存在");
        }

        Department department1 = departmentDao.findById(department);
        if (!user.setUsername(username).setPwd(pwd).setGender(gender).setBirthday(birthday).setRecordTime(recordTime).setIdCard(idCard).setArea(area).setNativePlace(nativePlace).setState(state).setDepartment(department).setDName(department1.getDName()).setLevel(leve).setAdmin(admin).save()) {
            return Ret.by("status", false).set("msg", "emp表异常");
        } else {

            if (leve.equals("部门经理")) {
                User manager = userDao.findById(department1.getManager());
                if (manager != null) {
                    if (!manager.setLevel("员工").update()) {
                        return Ret.by("status", false).set("msg", "替换经理出错");
                    }
                }
                if (!department1.setManager(user.getId()).setMName(user.getUsername()).update()) {
                    return Ret.by("status", false).set("msg", "部门表异常");
                }
            }

            Entry entry = new Entry();
            if (!entry.setEmp(user.getId()).setDepartment(department1.getId()).setTime(recordTime).setEmpName(user.getUsername()).setDName(department1.getDName()).save()) {
                return Ret.by("status", false).set("msg", "入职吧异常");
            }
            return Ret.by("status", true);
        }
    }

    public Ret newTransfer(int emp, String state, int department, String level, String admin, boolean badmin) {
        User user = userDao.findById(emp);
        if (user == null || user.getState().equals("离职")) {
            return Ret.by("status", false).set("msg", "员工不存在或已离职");
        }
        if ((user.getState().equals(state)) && (user.getDepartment() == department) && (user.getLevel().equals(level)) && (user.getAdmin() == badmin)) {
            return Ret.by("status", false).set("msg", "员工状态并未改变");
        }
        String stateBefore = user.getState();
        String levelBefore = user.getLevel();
        Department departmentBefore = departmentDao.findById(user.getDepartment());
        Department department1 = departmentDao.findById(department);
        if (department1.getId() != departmentBefore.getId()) {
            if (user.getId() == departmentBefore.getManager()) {
                if (!departmentBefore.setManager(null).setMName(null).update()) {
                    return Ret.by("status", false).set("msg", "替换经理出错");
                }
            }
            if (level.equals("部门经理")) {
                User manager = userDao.findById(department1.getManager());
                if (manager != null) {
                    if (!manager.setLevel("员工").update()) {
                        return Ret.by("status", false).set("msg", "替换经理出错");
                    }
                }
            }

        } else {
            if (user.getLevel().equals("部门经理") && !level.equals("部门经理")) {

                if (!departmentBefore.setManager(null).setMName(null).update()) {
                    return Ret.by("status", false).set("msg", "替换经理出错");
                }
            }
        }

        if (level.equals("部门经理")) {

            if (!department1.setManager(user.getId()).setMName(user.getUsername()).update()) {
                return Ret.by("status", false).set("msg", "部门表异常");
            }
        }


        if (!user.setState(state).setDepartment(department).setDName(department1.getDName()).setLevel(level).setAdmin(badmin).update()) {
            return Ret.by("status", false).set("msg", "user表异常");
        }


        Tranfer tranfer = new Tranfer();
        if (!tranfer.setEmp(emp).setEmpName(user.getUsername()).setDNameBefore(departmentBefore.getDName()).setStateBefore(stateBefore).setLevelBefore(levelBefore).setDName(department1.getDName()).setState(state).setLevel(level).setAdmin(admin).setTime(new Date()).save()) {
            return Ret.by("status", false).set("msg", "transfer表异常");
        }
        return Ret.by("status", true);
    }

    public Ret newDepartment(String dName, String mission, String remarks, int manager) {
        User one;
        if (manager != 0) {
            List<User> users = userDao.find(userDao.getSqlPara("user.findById", manager));
            if (users.isEmpty()) {
                return Ret.by("status", false).set("msg", "无此在职员工");
            } else {
                one = users.get(0);
                if (one.getState().equals("离职")) {
                    return Ret.by("status", false).set("msg", "此员工已离职");

                }

            }
        } else {
            Department department = new Department();
            if (department.setDName(dName).setMission(mission).setRemarks(remarks).save()) {
                return Ret.by("status", true);
            } else {
                return Ret.by("status", false).set("msg", "department表异常");
            }
        }

        Department department = new Department();
        if (department.setDName(dName).setMission(mission).setRemarks(remarks).setManager(one.getId()).setMName(one.getUsername()).save()) {


            Tranfer tranfer = new Tranfer();
            if (!tranfer.setEmp(one.getId()).setEmpName(one.getUsername()).setDNameBefore(one.getDName()).setStateBefore(one.getState()).setLevelBefore(one.getLevel()).setDName(dName).setState(one.getState()).setAdmin("否").setLevel("部门经理").setTime(new Date()).save()) {
                return Ret.by("status", false).set("msg", "transfer表异常");
            }
            if (one.setDepartment(department.getId()).setDName(dName).setLevel("部门经理").update()) {
                return Ret.by("status", true);
            }
            return Ret.by("status", false).set("msg", "user表异常");
        } else {
            return Ret.by("status", false).set("msg", "department表异常");
        }
    }

    public Ret newDimission(String reason, User user) {
        Dimission dimission = new Dimission();
        Department department = departmentDao.findById(user.getDepartment());
        if (!dimission.setEmp(user.getId()).setEmpName(user.getUsername()).setDepartment(user.getDepartment()).setDName(department.getDName()).setTime(new Date()).setReason(reason).setType("辞职").setPromoter(user.getId()).save()) {

            return Ret.by("status", false).set("msg", "dimission表异常");
        } else {
            return Ret.by("status", true);
        }
    }

    public Ret editDepartment(int id, String mission, String remarks) {
        Department department = departmentDao.findById(id);
        if (!department.setMission(mission).setRemarks(remarks).update()) {

            return Ret.by("status", false).set("msg", "department表异常");
        } else {
            return Ret.by("status", true);
        }
    }

    public Ret deleteDepartment(int id) {
        List<User> users = userDao.find(userDao.getSqlPara("user.findByDepartment", id));
        if (!users.isEmpty()) {
            return Ret.by("status", false).set("msg", "该部门下仍有员工");
        }
        Department department = departmentDao.findById(id);
        if (!department.delete()) {
            return Ret.by("status", false).set("msg", "department表异常");
        }
        return Ret.by("status", true);
    }

    public Ret newFire(int id, User user, String reason) {
        User fire = userDao.findById(id);
        if (fire.getDepartment() != (user.getDepartment()) || fire.getState().equals("离职")) {
            return Ret.by("status", false).set("msg", "该部门下无此员工");
        }
        Dimission dimission = new Dimission();
        if (!dimission.setEmp(fire.getId()).setEmpName(fire.getUsername()).setDepartment(fire.getDepartment()).setDName(fire.getDName()).setReason(reason).setTime(new Date()).setType("开除").setPromoter(user.getId()).save()) {
            return Ret.by("status", false).set("msg", "dimission表异常");
        } else {
            return Ret.by("status", true);
        }
    }

    public Ret agreeDimission(int id) {
        Dimission dimission = dimissionDao.findById(id);
        if (!dimission.setStatus("已批准").update()) {
            return Ret.by("status", false).set("msg", "dimission表异常");
        } else {


            User user = userDao.findById(dimission.getEmp());


            Tranfer tranfer = new Tranfer();
            if (!tranfer.setEmp(user.getId()).setEmpName(user.getUsername()).setDNameBefore(user.getDName()).setStateBefore(user.getState()).setLevelBefore(user.getLevel()).setDName(user.getDName()).setState("离职").setAdmin("否").setLevel(user.getLevel()).setTime(new Date()).save()) {
                return Ret.by("status", false).set("msg", "transfer表异常");
            }


            if (!user.setState("离职").update()) {
                return Ret.by("status", false).set("msg", "user表异常");
            }

            return Ret.by("status", true);


        }
    }

    public Ret refuseDimission(int id) {
        Dimission dimission = dimissionDao.findById(id);
        if (!dimission.setStatus("已拒绝").update()) {
            return Ret.by("status", false).set("msg", "dimission表异常");
        } else {
            return Ret.by("status", true);
        }
    }

    public Ret deleteDimission(int id, User user) {
        Dimission dimission = dimissionDao.findById(id);
        if (dimission.getPromoter() != user.getId()) {
            return Ret.by("status", false).set("msg", "您非此离职发起者");
        }
        if (!dimission.setStatus("用户撤销").update()) {
            return Ret.by("status", false).set("msg", "dimission表异常");
        } else {
            return Ret.by("status", true);
        }
    }
}
